<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="700px">
      <el-form status-icon :model="state.ruleForm" ref="ruleFormRef" size="default" :rules="rules"
               label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="姓名 :" prop="name">
              <el-input v-model="state.ruleForm.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="学号 :" prop="id">
              <el-input :disabled="state.dialog.type==='edit'" v-model="state.ruleForm.id" placeholder="请输入学号"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <div style="display: flex; justify-content: center; align-items: center"
                 @click="state.imageDialog = !state.imageDialog">
              <el-tooltip content="点击更换头像" placement="right" effect="light">
                <el-avatar :size="100" :src="state.src"/>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="邮箱 :" prop="email">
              <el-input v-model="state.ruleForm.email" placeholder="请输入邮箱" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="联系方式 :" prop="phone">
              <el-input v-model="state.ruleForm.phone" placeholder="请输入联系方式" clearable></el-input>
            </el-form-item>
          </el-col>
          <template v-if="state.dialog.type === 'edit'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="个人主页" prop="homePage">
                <el-input v-model="state.ruleForm.homePage" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="工作情况" prop="job">
                <el-input v-model="state.ruleForm.job" clearable></el-input>
              </el-form-item>
            </el-col>

          </template>


          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="学院专业 :" prop="schoolMajor">
              <el-cascader v-model="state.ruleForm.schoolMajor" :options="state.SchoolMajorOptions"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="研究方向 :" prop="domain">
              <el-cascader v-model="state.ruleForm.domain" :options="state.DomainOptions"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="个人简介" prop="description">
              <el-input v-model="state.ruleForm.description" type="textarea" placeholder="成员简介（20字以内）"
                        maxlength="150"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <el-dialog title="图片上传" v-model="state.imageDialog" width="900px">
        <cropper-image-upload :imgUrl="state.src" @uploadImgSuccess="uploadImgSuccessHandler"></cropper-image-upload>
      </el-dialog>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemUserDialog">
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import qiniu from "/@/utils/qiniu.js";
import Cookies from "js-cookie";
import {addUserInfo, updateUser} from "/@/views/user/users";
import CropperImageUpload from "/@/components/cropperUtil/component/cropper-image-upload.vue";
// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);
const rules = reactive({
  name: [{
    required: true,
    message: '请输入姓名',
    trigger: 'blur'
  }, {
    min: 2,
    max: 10,
    message: '姓名长度在2到10个字符之间',
    trigger: 'blur'
  }],
  phone: [{
    required: true,
    pattern: /^\d{11}$/,
    message: '联系方式必须为11位数字',
    trigger: 'blur'
  }],
  email: [{
    required: true,
    type: "email",
    message: '请输入有效的邮箱地址',
    trigger: 'blur'
  }],
  schoolMajor: [{required: true}],
  domain: [{required: true}]
  // description: [{ required: true, validator: validatorDescription, trigger: "blur" }]
});

const uploadImgSuccessHandler = function (data: any) {
  state.src = data || state.src;
  state.imageDialog = false;
};
const dataURLtoBlob = (dataurl: any) => {
  const arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime});
};


// 定义变量内容
const ruleFormRef = ref();
const state = reactive({
  SchoolMajorOptions: [],
  DomainOptions: [],
  imageDialog: false,
  src: "http://img.pzhuweb.cn/avatar",
  ruleForm: {
    id: "",
    name: "",
    password: "",
    passwordConfirm: "",
    email: "",
    phone: "",
    job: "",
    homePage: "",
    good: "",
    schoolMajor: [],
    domain: [],
    avatar: "",
    description: ""
  },
  fileList: [], // 上传文件列表
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: ""
  }
});
// 打开弹窗
const openDialog = (type: string, row: any, data: any) => {

  state.SchoolMajorOptions = data.schoolmajor;
  state.DomainOptions = data.domain;
  if (type === "edit") {
    let user = row.user
    state.ruleForm.id = row.id;
    state.ruleForm.name = user.name;
    state.ruleForm.email = user.email;
    state.ruleForm.phone = row.phone;
    state.ruleForm.job = row.job;
    state.ruleForm.homePage = row.homePage;
    state.ruleForm.description = row.description;
    state.src = row.avatar || state.src;
    state.ruleForm.schoolMajor = [row.school.id, row.major.id];
    state.ruleForm.domain = [row.domain.id];
    state.dialog.type = "edit";
    state.dialog.title = "修改成员";
    state.dialog.submitTxt = "修 改";
  } else {
    state.dialog.title = "新增成员";
    state.dialog.submitTxt = "新 增";
    state.ruleForm = {};
    state.src = "http://img.pzhuweb.cn/avatar";
    state.dialog.type = "add";
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = (e) => {

  handelSave(e);
  emit("refresh");
};


const handelSave = (e) => {
  e.preventDefault();
  ruleFormRef.value.validate((valid) => {
    console.log(valid);
    if (valid) {
      closeDialog();
      // loading.value = true;
      // 判断图片资源是本地的,还是第三方资源链接
      const strRegex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)/;
      const re = new RegExp(strRegex);
      if (!re.test(state.src)) {
        const dataBlob = dataURLtoBlob(state.src);
        const files = new File([dataBlob], Cookies.get("yourStuNum") + "tx", {
          type: dataBlob.type
        });
        qiniu(dataBlob)
            .then((res) => {
              state.src = res.key;
              if (state.dialog.type === "add") {
                addUserInfo({
                  id: state.ruleForm.id,
                  password: state.ruleForm.password,
                  name: state.ruleForm.name,
                  email: state.ruleForm.email,
                  phone: state.ruleForm.phone,
                  schoolMajor: state.ruleForm.schoolMajor,
                  domain: state.ruleForm.domain[0],
                  description: state.ruleForm.description,
                  avatar: state.src,
                  isCDN: 1
                })
                    .then((res) => {
                      if (res.success) {
                        setTimeout(() => {
                          emit("refresh");
                        }, 500);
                      }
                    });
              }
              if (state.dialog.type === "edit") {
                updateUser({
                  id: state.ruleForm.id,
                  name: state.ruleForm.name,
                  email: state.ruleForm.email,
                  phone: state.ruleForm.phone,
                  job: state.ruleForm.job,
                  homePage: state.ruleForm.homePage,
                  good: state.ruleForm.good,
                  schoolMajor: state.ruleForm.schoolMajor,
                  domain: state.ruleForm.domain[0],
                  description: state.ruleForm.description,
                  avatar: state.src,
                  isCDN: 1
                })
                    .then((res) => {
                      if (res.success) {
                        setTimeout(() => {
                          emit("refresh");
                        }, 500);
                      }
                    });
              }
            })
            .catch((err) => {
              ElMessage({
                message: "头像保存失败 !!!",
                type: "error"
              });
            });
      } else {
        if (state.dialog.type === "add") {
          addUserInfo({
            id: state.ruleForm.id,
            password: state.ruleForm.password,
            name: state.ruleForm.name,
            email: state.ruleForm.email,
            phone: state.ruleForm.phone,
            schoolMajor: state.ruleForm.schoolMajor,
            domain: state.ruleForm.domain[0],
            description: state.ruleForm.description,
            avatar: state.src,
            isCDN: 0
          })
              .then((res) => {
                if (res.success) {
                  setTimeout(() => {
                    emit("refresh");
                  }, 500);
                }
              });
        }
        if (state.dialog.type === "edit") {
          updateUser({
            id: state.ruleForm.id,
            name: state.ruleForm.name,
            email: state.ruleForm.email,
            phone: state.ruleForm.phone,
            job: state.ruleForm.job,
            homePage: state.ruleForm.homePage,
            good: state.ruleForm.good,
            schoolMajor: state.ruleForm.schoolMajor,
            domain: state.ruleForm.domain[0],
            description: state.ruleForm.description,
            avatar: state.src,
            isCDN: 0
          })
              .then((res) => {
                if (res.success) {
                  setTimeout(() => {
                    emit("refresh");
                  }, 500);
                }
              });
        }
      }
    } else {
      ElMessage({
        message: "信息填写有误 !!!",
        type: "error"
      });
    }
  });
};
// 暴露变量
defineExpose({
  openDialog
});
</script>
